package o2o.web.actions.sys;


import com.jinyou.utils.common.*;
import o2o.cache.sys.SysCustomerCache;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.MongoDaoImpl;
import o2o.config.dao.UserDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.sys.SysCustomerInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.web.actions.user.User;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import version.SysAppVersion;
import version.SysAppVersionLog;
import version.SysAppVersionMemory;
import version.SysAppVersionVO;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//版本控制
@Controller
public class SysAppVersionAction {
    private static final int ANDROIDUser = 1;//Android用户端
    private static final int ANDROIDShop = 2;//Android店铺端
    private static final int ANDROIDPostman = 3;//Android配送端
    private static final int IOSUser = 4;//ios用户端
    private static final int IOSShop = 5;//ios店铺端
    private static final int IOSPostman = 6;//ios配送端

    //获取版本
    @RequestMapping(method = RequestMethod.POST, value = "/version/get")
    @ResponseBody
    public String system_version(Integer typeId, String currVersion, String currVersionCode) {
//        if (ValidateUtil.isNull(currVersion) && ValidateUtil.isNull(currVersionCode)) {
//            return AjaxResult.errorResult("版本号为空");
//        }
        if (typeId < 1) {
            return AjaxResult.errorResult("获取更新类型不能为空");
        }

        //获取最新版本
        SysAppVersion sysAppVersion = SysAppVersionMemory.getInstance().getAppVersion(typeId);
        if (null == sysAppVersion) {
            return AjaxResult.errorResult("未获取到当前类型的应用信息");
        }

        SysAppVersionVO vo = new SysAppVersionVO();
        try {
            ObjectUtils.copyPropertiesExclude(sysAppVersion, vo, null);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取更新失败，请稍后再试");
        }
        if (null != vo) {
            return AjaxResult.successResult(vo);
        }

        return AjaxResult.successResult(sysAppVersion);
    }


    //更新版本
    @RequestMapping(method = RequestMethod.POST, value = "/version/update")
    @ResponseBody
    public String system_version_update(String token, SysAppVersion info) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasSuperAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有管理权限，请使用超级管理员账号登录");
        }

        if (null == info) {
            return AjaxResult.errorResult("请补全信息");
        }

        if (ValidateUtil.isNotAbsInteger(info.getTypeId())) {
            return AjaxResult.errorResult("请输入需要更新的应用类型");
        }
        if (ValidateUtil.isNull(info.getCurrVersion()) || ValidateUtil.isNull(info.getCurrVersionCode())) {
            return AjaxResult.errorResult("请输入应用版本");
        }


        //获取当前版本信息
        SysAppVersion sysAppVersion = SysAppVersionMemory.getInstance().getAppVersion(info.getTypeId());
        if (null == sysAppVersion) {//当前版本不存在
            return AjaxResult.errorResult("当前应用类型不存在，请检查");
        }
        if (ValidateUtil.isNotAbsInteger(info.getIsShow())) {
            info.setIsShow(sysAppVersion.getIsShow());
        }
        if (ValidateUtil.isNotAbsInteger(info.getIsForce())) {
            info.setIsForce(sysAppVersion.getIsForce());
        }

        if (ValidateUtil.isNull(info.getUpdateUrl())) {
            info.setUpdateUrl(sysAppVersion.getUpdateUrl());
        }


        //更新
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(SysAppVersionMemory.TABLENAME).append(" set updateUrl = '").append(info.getUpdateUrl())
                .append("',currVersion='").append(info.getCurrVersion())
                .append("',currVersionCode = '").append(info.getCurrVersionCode())
                .append("',isShow = ").append(info.getIsShow()).append(",isForce = ").append(info.getIsForce())
                .append(",note='").append(info.getNote()).append("',updateUser='").append(user.getUsername())
                .append("' where delFlag = 0 and typeId = ").append(info.getTypeId());
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("更新失败，请稍后再试");
        }
        //更新缓存
//        SysAppVersionMemory.getInstance().update(info.getTypeId());

        return AjaxResult.successResult();
    }


    //新增版本
    @RequestMapping(method = RequestMethod.POST, value = "/version/add")
    @ResponseBody
    public String system_version_add(String token, SysAppVersion info) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasSuperAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有管理权限，请使用超级管理员账号登录");
        }

        if (null == info) {
            return AjaxResult.errorResult("请补全信息");
        }

        if (ValidateUtil.isNotAbsInteger(info.getTypeId())) {
            return AjaxResult.errorResult("请输入需要新增的应用类型");
        }
        if (ValidateUtil.isNull(info.getCurrVersion()) || ValidateUtil.isNull(info.getCurrVersionCode())) {
            return AjaxResult.errorResult("请输入应用版本");
        }


        //获取当前版本信息
        SysAppVersion sysAppVersion = SysAppVersionMemory.getInstance().getAppVersion(info.getTypeId());
        if (null != sysAppVersion) {//当前版本不存在
            return AjaxResult.errorResult("当前应用类型已存在，请检查");
        }
        if (ValidateUtil.isNotAbsInteger(info.getIsShow())) {
            return AjaxResult.errorResult("请输入是否需要显示更新");
        }
        if (ValidateUtil.isNotAbsInteger(info.getIsForce())) {
            return AjaxResult.errorResult("请输入是否需要强制更新");
        }

        if (ValidateUtil.isNull(info.getUpdateUrl())) {
            return AjaxResult.errorResult("请输入应用更新地址");
        }
        Long time = DateUtils.getCurrTime();
        info.setCreateTime(time);
        info.setCreateUser(user.getUsername());
        info.setDelFlag(0);


        try {
            UserDaoSql.getInstance().insertObj(SysAppVersionMemory.TABLENAME, info);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("更新失败，请稍后再试");
        }
//        //更新缓存
//        SysAppVersionMemory.getInstance().add(time);

        return AjaxResult.successResult();
    }


    //删除版本
    @RequestMapping(method = RequestMethod.POST, value = "/version/delete")
    @ResponseBody
    public String system_version_delete(String token, Integer typeId) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasSuperAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有管理权限，请使用超级管理员账号登录");
        }

        if (ValidateUtil.isNotAbsInteger(typeId)) {
            return AjaxResult.errorResult("请输入应用类型");
        }

        //更新数据库
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(SysAppVersionMemory.TABLENAME).append(" set delFlag = 1 ,updateUser = '")
                .append(user.getUsername()).append("' where delFlag = 0 and typeId = ").append(typeId);
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除失败，请稍后再试");
        }
        //更新缓存
//        SysAppVersionMemory.getInstance().delete(typeId);


        return AjaxResult.successResult();
    }


    //管理员获取所有版本
    //获取所有版本
    @RequestMapping(method = RequestMethod.POST, value = "/admin/version/list")
    @ResponseBody
    public String system_version_list(String token) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasSuperAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有管理权限，请使用超级管理员账号登录");
        }

        List<SysAppVersion> list = SysAppVersionMemory.getInstance().getAppVersionList();
        if (ValidateUtil.isAbsList(list)) {
            List<SysAppVersionVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                SysAppVersionVO sysAppVersionVO = new SysAppVersionVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), sysAppVersionVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == sysAppVersionVO) {
                    continue;
                }
                voList.add(sysAppVersionVO);
            }

            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList.size(), voList);
            }
        }

        return AjaxResult.successResult(0, null);
    }


    //    /**
//     * 用户版本获取
//     */
//    @RequestMapping(method = RequestMethod.POST, value = "/version/get_old")
//    @ResponseBody
//    public String system_version(long typeId, String currVersion) {
//        if (currVersion == null || currVersion.equals("") || typeId < 1) {
//            return AjaxResult.errorNETResult();
//        }
//        int isUpdate = 0;
//        SysAppVersion version = SysVersionMemory.getInstance().get(typeId);
//        StringBuffer buffer = null;
//        if (version != null) {
//            String url = version.getUpdateUrl();
//            String currVersionDB = version.getCurrVersion();
//
//            if (ValidateUtil.isNotNull(currVersionDB) && !currVersion.equals(currVersionDB)) {
//                buffer = new StringBuffer("{\"status\":1,\"isUpdate\":1,\"updateUrl\":\"").append(url).append("\"}");
//            } else {
//                buffer = new StringBuffer("{\"status\":1,\"isUpdate\":0,\"updateUrl\":\"").append("").append("\"}");
//            }
//        } else {
//            buffer = new StringBuffer("{\"status\":1,\"isUpdate\":0,\"updateUrl\":\"").append("").append("\"}");
//        }
//        return buffer.toString();
//    }
//
//
//    //更新版本
//    @RequestMapping(method = RequestMethod.POST, value = "/version/update_e")
//    @ResponseBody
//    public String system_version_update(int typeId, String currVersion, String updateUrl, Integer isShow, Integer isFource) {
//        if (ValidateUtil.isNull(updateUrl) || ValidateUtil.isNull(currVersion) || typeId < 1) {
//            return AjaxResult.errorNETResult();
//        }
//
//        //更新版本
//        String sql = "update " + SysVersionMemory.AppVerTable + " set currVersion='" + currVersion + "',updateUrl='" + updateUrl + "'"
//                + (isShow != null ? ",isShow=" + isShow : "")
//                + (isFource != null ? ",isFource=" + isFource : "")
//                + " where typeId=" + typeId;
//        try {
//            UserDaoSql.getInstance().executeBySql(sql);
//        } catch (SQLException e) {
//            e.printStackTrace();
//            return AjaxResult.errorNET2Result();
//        }
//
//        //更新缓存--同步数据
//        JMSNotify notify = JMSNotify.getInstance().setType(JMSNotify.AppVersionModify).setInt01(typeId);
//        JmsSender.setTopicSender(notify);
//
//        return AjaxResult.successResult();
//    }

    // app升级的log
    @Async
    public void save_version_app_log(String updateUrl, Integer typeId, String currVersion, String currVersionCode, Integer isShow, Integer isForce, String note) {
        SysAppVersionLog sysAppVersionLog = new SysAppVersionLog(updateUrl, typeId, currVersion, currVersionCode, isShow, isForce, note);
        Map<String, Object> mm = ObjectUtils.beanToMap(sysAppVersionLog);
        try {
            MongoDaoImpl.getInstance().insert("o2o_app_log", "app_log", mm);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //======================================base系统  =======================
    //更新版本
    @RequestMapping(method = RequestMethod.POST, value = "/base/version/update")
    @ResponseBody
    public String base_system_version_update(String apiKey, String sysAppKey, SysAppVersion info) {
        SysCustomerInfo customerInfo = new SysCustomerInfo();
        try {
            String decrypt = EncrypAES.aesDecrypt(apiKey, "abcdefgabcdeg12p");
            if (ValidateUtil.isNull(sysAppKey)) {
                sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
            }

            customerInfo = SysCustomerCache.getInstance().getInfo(sysAppKey);
            if (null != customerInfo) {
                if (!decrypt.equals(customerInfo.getApiKey())) {
                    return AjaxResult.errorResult("您没有访问权限");
                }
            } else {
                return AjaxResult.errorResult("没有客户信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }

        if (null == info) {
            return AjaxResult.errorResult("请补全信息");
        }

        if (ValidateUtil.isNotAbsInteger(info.getTypeId())) {
            return AjaxResult.errorResult("请输入需要更新的应用类型");
        }
        if (ValidateUtil.isNull(info.getCurrVersion()) || ValidateUtil.isNull(info.getCurrVersionCode())) {
            return AjaxResult.errorResult("请输入应用版本");
        }


        //获取当前版本信息
        SysAppVersion sysAppVersion = SysAppVersionMemory.getInstance().getAppVersion(info.getTypeId());
        if (null == sysAppVersion) {//当前版本不存在
            return AjaxResult.errorResult("当前应用类型不存在，请检查");
        }
        if (ValidateUtil.isNotAbsInteger(info.getIsShow())) {
            info.setIsShow(sysAppVersion.getIsShow());
        }
        if (ValidateUtil.isNotAbsInteger(info.getIsForce())) {
            info.setIsForce(sysAppVersion.getIsForce());
        }

        if (ValidateUtil.isNull(info.getUpdateUrl())) {
            info.setUpdateUrl(sysAppVersion.getUpdateUrl());
        }

        //更新
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(SysAppVersionMemory.TABLENAME).append(" set updateUrl = '").append(info.getUpdateUrl())
                .append("',currVersion='").append(info.getCurrVersion())
                .append("',currVersionCode = '").append(info.getCurrVersionCode())
                .append("',isShow = ").append(info.getIsShow()).append(",isForce = ").append(info.getIsForce())
                .append(",note='").append(info.getNote()).append("',updateUser='").append("base")
                .append("' where delFlag = 0 and typeId = ").append(info.getTypeId());
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("更新失败，请稍后再试");
        }
        //更新缓存
//        SysAppVersionMemory.getInstance().update(info.getTypeId());

        return AjaxResult.successResult();
    }

    //获取所有版本
    @RequestMapping(method = RequestMethod.POST, value = "/base/version/list")
    @ResponseBody
    public String base_system_version_list(String apiKey, String sysAppKey) {
        //验证用户有效性
        SysCustomerInfo customerInfo = new SysCustomerInfo();
        try {
            String decrypt = EncrypAES.aesDecrypt(apiKey, "abcdefgabcdeg12p");
            if (ValidateUtil.isNull(sysAppKey)) {
                sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
            }

            customerInfo = SysCustomerCache.getInstance().getInfo(sysAppKey);
            if (null != customerInfo) {
                if (!decrypt.equals(customerInfo.getApiKey())) {
                    return AjaxResult.errorResult("您没有访问权限");
                }
            } else {
                return AjaxResult.errorResult("没有客户信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }

        List<SysAppVersion> list = SysAppVersionMemory.getInstance().getAppVersionList();
        if (ValidateUtil.isAbsList(list)) {
            List<SysAppVersionVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                SysAppVersionVO sysAppVersionVO = new SysAppVersionVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), sysAppVersionVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == sysAppVersionVO) {
                    continue;
                }
                voList.add(sysAppVersionVO);
            }

            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList.size(), voList);
            }
        }

        return AjaxResult.successResult(0, null);
    }

    //新增更新版本记录
    @RequestMapping(method = RequestMethod.POST, value = "/admin/version/log/add")
    @ResponseBody
    public String SysAppVersionLogAdd(SysAppVersionLog info) {
        //创建时间
        long time = DateUtils.getCurrTime();
        info.setCreateTime(time);
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.APP_VERSION_LOG, info);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return AjaxResult.successResult();
    }

    //查询更新版本记录
    @RequestMapping(method = RequestMethod.POST, value = "/admin/version/log/list")
    @ResponseBody
    public String SysAppVersionLogList(Integer typeId){
        if(typeId==null){
            return AjaxResult.errorResult("请传入应用类型");
        }
        QueryCondition query = QueryCondition.getInstance();
        query.addCondition(Expression.getInstance().addChild("typeId", typeId));
        String sql = DaoUtils.getSql(PojoTables.APP_VERSION_LOG, query);
        List<SysAppVersionLog> list = null;
        try {
            list = (List<SysAppVersionLog>) UserDaoSql.getInstance().list(SysAppVersionLog.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (ValidateUtil.isAbsList(list)) {
            list.sort((a, b) -> (int) (b.getId() - a.getId()));
            return  AjaxResult.successResult(list);
        }

        return  AjaxResult.successResult(list);
    }


}
